// pages/landmark/landmark.js
import { HTTP } from '../../utils/http.js'
import api from '../../utils/api.js'
import { config } from '../../utils/config'
let http = new HTTP()

Page({
    /**
     * 页面的初始数据
     */
    data: {
        mask: false,
        imgUrl: config.imgUrl,
        carList: [],
        totalPrice: 0.00, //总价
        checkAll: true, //全选中
        changeColor: 1, //品牌选中id
        startX: 0, //开始坐标
        startY: 0,
        isFind: false

    },
    //计算总价
    totalAll(list) {
        var num = 0;
        list.forEach((key, index) => {
            if (key.check) {
                num += key.price * key.num
            }
        })
        this.setData({
            totalPrice: num.toFixed(2)
        })
    },
    //下单
    toOrder() {
        var list = this.data.carList,
            payList = [],
            bool = false;
        console.log('全部商品', list);
        /*清空payList*/
        wx.removeStorageSync('payList');

        list.forEach((key) => {
            if (key.check) {
                payList.push({ 'product_id': key.product_id, 'name': key.product_name, 'num': key.num })
            }

        })
        console.log('已选蔬菜', payList)
        payList.length == 0 ? bool = false : bool = true
        if (bool) {
            wx.setStorageSync('payList', payList)
            wx.navigateTo({
                url: "/pages/recommendShopList/recommendShopList?type=1"
            })
            // this.setData({
            //     checkAll: false,
            //     totalPrice: 0.00
            // })
        }

        // console.log(payList)

    },
    //选择品牌
    showMask() {
        this.setData({
            mask: true
        })
    },
    //选中品牌
    checkBrand(e) {
        console.log()
        this.setData({
            changeColor: e.currentTarget.dataset.id
        })
    },
    //关闭蒙层
    closeMask() {
        this.setData({
            mask: false
        })
    },
    //更改品牌
    changeBrand() {
        this.closeMask()
    },
    goLook() {
        wx.reLaunch({
            url: "/pages/index/index"
        })
    },
    //删除菜篮数据
    deleteItem(e) {
        var id = e.currentTarget.dataset.id
        let _that = this;
        this.postEdit({ user_id: wx.getStorageSync("user_id"), product_id: id }, api.shoppingCartDelOne).then(res => {
            if (res.code == 200) {
                _that.onShow();
            }
        })
    },
    //编辑数量
    editNUms(e) {
        var index1 = e.currentTarget.dataset.index1,
            id = e.currentTarget.dataset.id,
            list = this.data.carList,
            type = e.currentTarget.dataset.type,
            newList = [],
            summary = e.currentTarget.dataset.summary;
        if (type == "sub") {
            if (list[index1].num > 1) {
                this.postEdit({ user_id: wx.getStorageSync("user_id"), product_id: id, summary: summary }, api.shoppingCartDel).then(res => {
                    console.log(res)
                    list[index1].num--
                    console.log(list[index1].num)
                    this.totalAll(list)
                    this.setData({
                        carList: list
                    })

                })
            } else {
                wx.showModal({
                    // title:"提示",
                    content: "确定删除该商品吗?",
                    success: (sm) => {
                        console.log(sm)
                        if (sm.confirm) {
                            this.deleteItem(index1, id)
                        }
                    }
                })
                // this.deleteItem(index1,id)
            }

        } else {
            this.postEdit({ user_id: wx.getStorageSync("user_id"), product_id: id, summary: summary }, api.shoppingCartAdd).then(res => {
                console.log(res)
                list[index1].num++
                console.log(list[index1].num)
                this.totalAll(list)
                this.setData({
                    carList: list
                })
            })

        }

    },
    postEdit(obj, url) {
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                data: obj,
                success: res => {
                    resolve(res);
                }
            })
        })
    },
    //全部选中
    checkAlls(e) {
        let bool = this.data.checkAll,
            list = this.data.carList;
        bool ? bool = false : bool = true
        list.forEach((key, index1) => {
            key.check = bool;
        })
        console.log(list)
        this.totalAll(list)
        this.setData({
            checkAll: bool,
            carList: list
        })
    },
    //单个选中
    single() {
        let all1 = 0,
            all2 = 0,
            all3 = 0,
            bool = false,
            list = this.data.carList;
        //全部选中
        list.forEach((key, index1) => {
            key.check ? all1++ : all1
        })
        all1 == list.length ? bool = true : bool = false
        this.totalAll(list)
        this.setData({
            checkAll: bool
        })

    },
    //菜品选中
    littleCheck(e) {
        let i = 0,
            checkAll;
        var list = this.data.carList,
            index1 = e.currentTarget.dataset.index1;
        list[index1].check = !list[index1].check;

        list.forEach((ele, index) => {
            ele.check ? i++ : i
        })
        i == list.length ? checkAll = true : checkAll = false
        this.totalAll(list)
        this.setData({
            carList: list,
            checkAll: checkAll
        })
    },
    //菜谱选中
    smallAll(e) {
        var list = this.data.carList,
            index = e.currentTarget.dataset.index;
        list[index].check == false ? list[index].check = true : list[index].check = false
        console.log(list)
        list[index].product.forEach((key, i) => {
            key.check = list[index].check
        });
        this.single()
        this.totalAll(list)
        this.setData({
            carList: list
        })
    },
    getOne(obj) {
        http.request({
            url: "",
            data: obj,
            success: res => {

            }
        })
    },

    getCarList() {
        this.getInfo(
            { user_id: wx.getStorageSync("user_id") },
            api.shoppingCartList,
        ).then(res => {
            if (res.code == 200) {
                var car = res.data.data;
                if (car.length > 0) {
                    car.forEach((key, index) => {
                        key.check = true;
                        key.isTouchMove = false;
                        if (key.main_img_url.indexOf('https') < 0) {
                            key.main_img_url = 'https://images.weigeee.com/' + key.main_img_url
                        }
                    })
                }
                this.setData({
                    carList: car
                })
            }
        })
    },

    //获取菜篮
    getInfo(obj, url) {
        let that = this
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                data: obj,
                success: res => {
                    resolve(res);
                    that.setData({
                        isFind: true
                    })
                }
            })
        })
    },

    //手指触摸动作开始 记录起点X坐标
    touchstart: function (e) {
        //开始触摸时 重置所有删除
        this.data.carList.forEach(function (v, i) {
            if (v.isTouchMove) //只操作为true的
                v.isTouchMove = false;
        })
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            carList: this.data.carList
        })
    },
    //滑动事件处理
    touchmove: function (e) {
        var that = this,
            index = e.currentTarget.dataset.index, //当前索引
            startX = that.data.startX, //开始X坐标
            startY = that.data.startY, //开始Y坐标
            touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
            touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
            //获取滑动角度
            angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
        that.data.carList.forEach(function (v, i) {
            v.isTouchMove = false
            //滑动超过30度角 return
            if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX) //右滑
                    v.isTouchMove = false
                else //左滑
                    v.isTouchMove = true
            }
        })
        //更新数据
        that.setData({
            carList: that.data.carList
        })
    },
    angle: function (start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    //删除事件
    del: function (e) {
        this.data.carList.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            carList: this.data.carList
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log(wx.getStorageSync("user_id"));
        this.getCarList();
        wx.wg_util.refreshShopCarBadge();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})